﻿#ifndef PST_SCREENCAPTUREWIDGET_H
#define PST_SCREENCAPTUREWIDGET_H

#include <QApplication>
#include <QWidget>
#include <QScreen>
#include <QPainter>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QClipboard>
#include <QGuiApplication>
#include <QEventLoop>
#include <QPushButton>
#include <QVBoxLayout>
#include <QLabel>

// 自定义截图窗口：支持多屏，完成截图后仅关闭自身，不退出程序
class ScreenCaptureWidget : public QWidget
{
    Q_OBJECT
public:
    explicit ScreenCaptureWidget(QWidget* parent = nullptr)
        : QWidget(parent)
    {
        // 获取主屏幕的几何信息
        QRect primaryScreenGeometry = QGuiApplication::primaryScreen()->geometry();
        // 覆盖主屏幕
        setGeometry(primaryScreenGeometry);
        setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
        setAttribute(Qt::WA_TranslucentBackground);
        setCursor(Qt::CrossCursor);
    }

signals:
    // 截图完成后发出信号，传递截图结果（空 QPixmap 表示取消）
    void captureFinished(const QPixmap& pixmap);

protected:
    // 绘制半透明背景并在用户拖动时显示选区矩形
    void paintEvent(QPaintEvent*) override
    {
        QPainter painter(this);
        // 半透明黑色背景，突出选区区域
        painter.fillRect(rect(), QColor(0, 0, 0, 100));

        if (showHint)
        {
            // 添加提示文字
            QFont font;
            font.setPointSize(16);
            painter.setFont(font);
            painter.setPen(Qt::white);
            QString text = "按ESC退出截图，按住鼠标左键拖动以选择截图范围";
            // 计算文字绘制的矩形区域，使其居中
            QRect textRect(0, 0, width(), 30);
            textRect.moveCenter(rect().center());
            painter.drawText(textRect, Qt::AlignCenter, text);
        }

        if (selectionRect.isValid())
        {
            // 擦除选中区域的半透明黑色背景
            painter.setCompositionMode(QPainter::CompositionMode_Source);
            painter.fillRect(selectionRect.normalized(), Qt::transparent);

            QPen pen(Qt::red, 2);
            painter.setPen(pen);
            painter.drawRect(selectionRect.normalized());
        }
    }

    // 记录鼠标左键按下起点
    void mousePressEvent(QMouseEvent* event) override
    {
        if (event->button() == Qt::LeftButton)
        {
            startPos = event->pos();
            selectionRect = QRect(startPos, QSize());
            showHint = false;
            update();
        }
    }

    // 鼠标移动时更新选区
    void mouseMoveEvent(QMouseEvent* event) override
    {
        if (event->buttons() & Qt::LeftButton)
        {
            selectionRect = QRect(startPos, event->pos()).normalized();
            update();
        }
    }

    // 鼠标释放后完成截图
    void mouseReleaseEvent(QMouseEvent* event) override
    {
        if (event->button() == Qt::LeftButton)
        {
            selectionRect = selectionRect.normalized();

            // 隐藏窗口，防止截取到本窗口自身
            hide();

            // 调用 processEvents 并加入短暂延时，让系统完成窗口隐藏和桌面合成的更新
            QGuiApplication::processEvents();
            QGuiApplication::processEvents();
            QGuiApplication::processEvents();
            QGuiApplication::processEvents();
            QGuiApplication::processEvents();
            QGuiApplication::processEvents();
            QThread::msleep(1150);  // 延时50毫秒，可根据需要调整

            // 获取主屏幕
            QScreen* primaryScreen = QGuiApplication::primaryScreen();
            // 获取主屏幕的几何信息
            QRect primaryScreenGeometry = primaryScreen->geometry();
            // 获取主屏幕的设备像素比率
            qreal devicePixelRatio = primaryScreen->devicePixelRatio();

            // 创建对应主屏幕的空白图像，并考虑设备像素比率
            QPixmap primaryScreenPixmap(primaryScreenGeometry.size() * devicePixelRatio);
            primaryScreenPixmap.setDevicePixelRatio(devicePixelRatio);
            primaryScreenPixmap.fill(Qt::black);

            QPainter painter(&primaryScreenPixmap);
            // 对主屏幕进行截图并考虑设备像素比率
            QPixmap screenPixmap = primaryScreen->grabWindow(0, 0, 0,
                                                             primaryScreenGeometry.width() * devicePixelRatio,
                                                             primaryScreenGeometry.height() * devicePixelRatio);
            screenPixmap.setDevicePixelRatio(devicePixelRatio);
            // 直接绘制主屏幕截图
            painter.drawPixmap(QPoint(0, 0), screenPixmap);
            painter.end();

            // 手动缩放选择区域
            QRect scaledSelectionRect(
                static_cast<int>(selectionRect.x() * devicePixelRatio),
                static_cast<int>(selectionRect.y() * devicePixelRatio),
                static_cast<int>(selectionRect.width() * devicePixelRatio),
                static_cast<int>(selectionRect.height() * devicePixelRatio));

            // 从主屏幕截图中剪切出用户选区，并考虑设备像素比率
            QPixmap captured = primaryScreenPixmap.copy(scaledSelectionRect);
            captured.setDevicePixelRatio(devicePixelRatio);
            QClipboard* clipboard = QGuiApplication::clipboard();
            clipboard->setPixmap(captured);

            emit captureFinished(captured);
            close();  // 关闭截图窗口，仅此而已，不退出整个程序
        }
    }

    // 按 Esc 取消截图，返回空 QPixmap
    void keyPressEvent(QKeyEvent* event) override
    {
        if (event->key() == Qt::Key_Escape)
        {
            emit captureFinished(QPixmap());
            close();
        }
    }

private:
    QPoint startPos;     // 记录鼠标起始点
    QRect selectionRect; // 当前选区矩形
    bool showHint{true};
};
#endif
